package com.logic.modular.gameCore.config.service.impl;


import com.baomidou.mybatisplus.extension.service.IService;
import com.comment.pojo.domain.logic.core.CoreAccountConfig;
import lombok.extern.slf4j.Slf4j;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.logic.modular.gameCore.config.mapper.CoreAccountConfigMapper;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
import javax.annotation.PostConstruct;


/**
 * 账户相关配置(CoreAccountConfig)表服务实现类
 *
 * @author cxy
 * @since 2024-08-07 10:00:19
 */
@Slf4j
@Service

public class CoreAccountConfigServiceImpl extends ServiceImpl<CoreAccountConfigMapper, CoreAccountConfig> implements IService<CoreAccountConfig> {
    private final static Cache<String, Map<Long,CoreAccountConfig>> cache = Caffeine.newBuilder().build();
    
    @PostConstruct
    private void init() {
        CoreAccountConfig initSelect = CoreAccountConfig.builder().build();
        List<CoreAccountConfig> list = this.list(new LambdaQueryWrapper<>(initSelect));
        log.info("开始缓存账户相关配置数据,数据量为:{}",list.size());
        cache.put(
                "coreAccountConfig", 
                list.stream().collect(Collectors.toMap(CoreAccountConfig::getId, CoreAccountConfig::init))
        );
        log.info("账户相关配置数据缓存完成");
    }

    public List<CoreAccountConfig> listCache() {
        Map<Long,CoreAccountConfig> values = cache.getIfPresent("coreAccountConfig");
        if (Objects.isNull(values)) {
            throw new RuntimeException("账户相关配置数据为空");
        }
        return new ArrayList<>(values.values());
    }     
    
    public Map<Long,CoreAccountConfig> mapCache() {
        Map<Long,CoreAccountConfig> values = cache.getIfPresent("coreAccountConfig");
        if (Objects.isNull(values)) {
            throw new RuntimeException("账户相关配置数据为空");
        }
        return values;
    }   
    
    public static CoreAccountConfig getCache(Long id) {
        Map<Long,CoreAccountConfig> values = cache.getIfPresent("coreAccountConfig");
        if (Objects.isNull(values)) {
            throw new RuntimeException("账户相关配置数据为空");
        }
        return values.get(id);
    }
}
